# flask web 网络编程文件
from flask import Flask, render_template, request, escape
from vsearch import search4letters
from mini import niceday

# html 调用方法：render_template  按照 jinja2 规则
app = Flask(__name__)

def log_request(req:'flask_request',res:str) ->None:
    with open('vsearch.log', 'a') as log:
        # print(str(dir(req)), res, file=log)
        # print(req.form,file=log,end='|')
        # print(req.remote_addr,file=log,end='|')
        # print(req.user_agent,file=log,end='|')
        # print(res,file=log)
        print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')

@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your results:'
    results = str(search4letters(phrase, letters))
    log_request(request,results)
    用户输入的姓名 = request.form['niceday']
    今日运势 = niceday(用户输入的姓名)
    return render_template('results.html',
                           the_title=title,
                           the_phrase=phrase,
                           the_letters=letters,
                           the_results=results,
                           the_niceday=今日运势,)

@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    title = '今日运势' \
            ''
    return render_template('entry.html',
                           the_title='Welcome to search4letters on the web!')
@app.route('/viewlog')
def view_the_log() -> 'html':
    """display the contents of thr log file as a html table"""
    contents = []
    with open('vsearch.log','r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    len(contents)
    titles = ('From Data','Remote_addr','User_agent','Results')
    return render_template('viewlog.html',
                           the_title='日志系统后台',
                           the_row_title=titles,
                           the_data=contents)
# @app.route('/viewlog')
# def view_the_log() ->'html':
#     contents = []
#     with open('vsearch.log','r') as log:
#         for line in log:
#             contents.append([])
#             for item in line.split('|'):
#                 contents[-1].append(escape(item))
#         len(contents)
#         titles = ('From Data','Remote_addr','User_agent','Results')
#         return render_template('viewlog.html',
#                                the_title='View Log',
#                                the_row_titles=titles,
#                                the_date=contents)
# def view_the_log() ->str:
#     with open('vsearch.log') as log:
#         contents = log.readlines()
#         return escape(''.join(contents))
if __name__ == '__main__':
    app.run(debug=True)
